import { Button, Form, Input, Popconfirm, Table, DatePicker, Select, InputNumber } from 'antd';
import React, { useEffect, useRef, useState,useMemo} from 'react';
import { openNotification_util, checkdatavalid_util, fetchsync_util, useCallbackState, addkey_for_mxdata } from '../util/util.js'
import Upload_hooks from '../newmes/upload_hooks.js'
import Popup_table_hooks_datas from '../newmes/popup_table_hooks_datas.js'
import { v4 as uuidv4 } from 'uuid';
import { FileAddOutlined, DeleteOutlined, CopyOutlined, ExperimentOutlined } from '@ant-design/icons';
import Customfielditem_hook from '../newmes/customfielditem_hook.js'

import moment from 'moment'
import locale from 'antd/lib/date-picker/locale/zh_CN'
import 'moment/locale/zh-cn'
moment.locale('zh-cn')

const { Option } = Select;



const Gpd_mx_hook = (props) => {
  const [dataSource, setDataSource] = useState([]);
  const [count, setCount] = useState(props.datasource.length + 2);
  const [selectedRows, setselectedRows] = useState([])
  const [selectedRowKeys, setselectedRowKeys] = useState([])
  const [columns, setcolumns] = useState([])
  const [wlmcdatasource, setwlmcdatasource] = useState([]);
  const [ifshowonepage, setifshowonepage] = useState("none")
  const [formdataoneepage, setformdataonepage] = useState({})
  const [type, setType] = useState()



  const handleDelete = (record) => {
    const newData = dataSource.filter((item) => item.key !== record.key);
    setDataSource(newData);
    props.handgetmxdata(newData)
    props.handledelid([record.id])
    //console.log("record.id", record.id)
  };



  const handleDeletebatch = () => {
    var newData = dataSource
    var idsarr = []
    selectedRows.forEach(recorditem => {
      //console.log(recorditem.key)
      newData = newData.filter((item) => item.key !== recorditem.key);
      idsarr.push(recorditem.id)
    })
    setDataSource(newData);
    props.handgetmxdata(newData)
    props.handledelid(idsarr)
    setselectedRows([])
    setselectedRowKeys([])
  }

  const handlecloseplan = () => {
    var newData = dataSource
    selectedRows.forEach((recorditem) => {
      newData.forEach(newdataitem => {
        if (newdataitem.key == recorditem.key) {
          newdataitem.djzt = "关闭"
        }
      })
    })
    props.handgetmxdata([...newData])
    setselectedRows([])
    setselectedRowKeys([])
  }




    useEffect(() => {
      setDataSource(props.datasource)
    }, [props.datasource])



  useEffect(() => {
    renrendercolumns()
  }, [dataSource, wlmcdatasource])


  useEffect(() => {
    if (ifshowonepage == "none") {
      var newformdataoneepage = formdataoneepage;
      for (var key in formdataoneepage) {
        newformdataoneepage[key].value = ""
      }
      setformdataonepage({ ...newformdataoneepage })
    }
    else {
      if (type == 'edit') {
        var newformdataoneepage = formdataoneepage;
        for (var key in newformdataoneepage) {
          newformdataoneepage[key].value = selectedRows[0][key];
        }
        setformdataonepage({ ...newformdataoneepage })
      }
      else {
        var newformdataoneepage = formdataoneepage;
        for (var key in formdataoneepage) {
          newformdataoneepage[key].value = ""
        }
        setformdataonepage({ ...newformdataoneepage })
      }
    }
  }, [ifshowonepage])



  useEffect(() => {
    //console.log("colmuns变化")
    var columnarr = props.colmuns;
    var newformdataonepage = {};
    columnarr.forEach(item => newformdataonepage[item.dataIndex] = item)
    setformdataonepage(newformdataonepage)
  }, [props.colmuns])


  const rowSelection = {
    selectedRowKeys: selectedRowKeys,
    onChange: (selectedRowKeys, selectedRows) => {

      setselectedRowKeys(selectedRowKeys)
      setselectedRows(selectedRows)
      props.handleselectMxdata(selectedRows )
    },
    getCheckboxProps: (record) => ({
      disabled: record.name === 'Disabled User',
      // Column configuration not to be checked
      name: record.name,
    }),
    selections: [
      Table.SELECTION_ALL,
      Table.SELECTION_INVERT,
      Table.SELECTION_NONE]
  };



  //自定义渲染
  const renrendercolumns = () => {

    var newcolumns = props.colmuns.filter(item => item.inputType !== "space_item"&&item.inputType !== "none").map((col) => {
      if(col.inputType !== "space_item"){

      if (col.inputType == "input_item"||col.inputType == "input_text_item") {
        col.render = (text, record, index) => {
            return col.uncontrol?<Input defaultValue={text} style={col.style ? col.style : {}}
            onBlur={e => { handleChangeinput(e, col.dataIndex, text, record, index) }} />
            :<Input value={text} style={col.style ? col.style : {}}
            onChange={e => { handleChangeinput(e, col.dataIndex, text, record, index) }} />
          }
      }
      else if (col.inputType == "popup_item_datas") {
        var datas=[]
        props.dynDatasObject?datas=props.dynDatasObject[col.datas_key]:""
        col.render = (text, record, index) => {
          return <Popup_table_hooks_datas viewname={col.popup_viewname} selecttype="radio" style={col.style ? col.style : {}}
            tablecolnum={col.popup_column} datas={datas}
            ifshow="none" popup_maintitle={col.popup_maintitle}
            handlechange={e => { handleChangepopup(e, col.popup_tansferarr, col.dataIndex, text, record, index) }}
            inputvalue={text} />
        }
      }
      else if (col.inputType == "input_number_item") {
        col.render = (text, record, index) => {
          return col.uncontrol? <InputNumber controls={false} max="22332233223322339" 
          style={col.style ? col.style : {width:col.width?col.width:"95%"}}
         defaultValue={text}
         onBlur={e => { handleChangeinputnumber(e, col.dataIndex, text, record, index) }}
         placeholder={`输入${col.title}...`}
       />
            : <InputNumber controls={false} max="22332233223322339" 
            style={col.style ? col.style : {width:col.width?col.width:"95%"}}
           value={text}
           onChange={e => { handleChangeinputnumber(e, col.dataIndex, text, record, index) }}
           placeholder={`输入${col.title}...`}
         />
        }
      }
      else if (col.inputType == "select_item") {
     col.render = (text, record, index) => {
          var optionitem = col.selectdata.map(obj => <Option value={obj.value}>{obj.label}</Option>)
          return <Select placeholder="" value={text} style={col.style ? col.style : {width:col.width?col.width:"95%"}}
            onSelect={e => { handleSelect(e, col.dataIndex, text, record, index) }}>
            {optionitem}
          </Select>
        }
      }

        else if (col.inputType == "select_item_new") {
        col.render = (text, record, index) => {

          return <Select placeholder="" value={text} style={col.style ? col.style : {width:col.width?col.width:"95%"}}
          showSearch
            onSelect={(e,extra) => { handleSelectNew(extra, col.popup_tansferarr, text, record, index,col.datas_key) }}
            options={props.dynDatasObject[col.datas_key]}

            />
        }
      }
 
      else if (col.inputType == "date_item") {
        col.render = (text, record, index) => {
          return <DatePicker locale={locale} value={text == "" ? "" : moment(text)} style={col.style ? col.style : {}}
            onChange={(e, datestring) => { handleChangedate(e, datestring, col.dataIndex, text, record, index) }} />
        }
      }

      else if (col.inputType == "upload_item") {
        col.render = (text, record, index) => {
          return <Upload_hooks handleback={tpurl => getchildvalue_upload(tpurl, col.dataIndex, text, record, index)}
            title="" initpxtpurl={text} />
        }
      }


      else if (col.inputType == "deletetool_item") {
        col.render = (text, record, index) => {
          return <Popconfirm title="确定要删除么?" onConfirm={() => handleDelete(record)}>
            <Button><a style={{ fontWeight: "600", color: "#C54444" }}>删 除</a></Button>
          </Popconfirm>
        }
      }
      else if (col.inputType == "readonly") {
        col.render = (text, record, index) => {
          return <Input value={text} disabled style={col.style ? col.style : {}}
          />
        }
      }

      return {
        ...col
      };
    }
    
    });


    //渲染必填
    newcolumns.forEach(item =>item.bt?item.title=<div><span style={{ color: "red" }}  >*</span>{item.title}</div>:"")
    setcolumns(newcolumns)
  }



  //从upload取值
  const getchildvalue_upload = (tpurl, dataIndex, text, record, index) => {

    var newdatasource = [...dataSource];
    const realindex = newdatasource.findIndex((item) => record.key === item.key);
    newdatasource[realindex][dataIndex] = tpurl;
    // setDataSource(newdatasource)
    props.handgetmxdata(newdatasource)
  }

  //监听日期
  const handleChangedate = (e, datestr, dataIndex, text, record, index) => {
    var newdatasource = [...dataSource];
    const realindex = newdatasource.findIndex((item) => record.key === item.key);
    newdatasource[realindex][dataIndex] = datestr;
    // setDataSource(newdatasource)
    props.handgetmxdata(newdatasource)
  }

  //监听输入及联动
  const handleChangeinput = (e, dataIndex, text, record, index) => {
    var newdatasource = [...dataSource];
    const realindex = newdatasource.findIndex((item) => record.key === item.key);
    newdatasource[realindex][dataIndex] = e.target.value;
    // setDataSource(newdatasource)
    props.handgetmxdata(newdatasource)
  }

    //监听输入及联动
    const handleChangeinputnumber = (e, dataIndex, text, record, index) => {
      var newdatasource = [...dataSource];
      const realindex = newdatasource.findIndex((item) => record.key === item.key);
      newdatasource[realindex][dataIndex] = e;
      if (newdatasource[realindex]['sl'] > 0 && newdatasource[realindex]['dj'] > 0 ) {
        newdatasource[realindex]['je'] = newdatasource[realindex]['sl'] * newdatasource[realindex]['dj']
      }
      if (newdatasource[realindex]['je'] > 0 && newdatasource[realindex]['shuil'] > 0 ) {
        newdatasource[realindex]['se'] = newdatasource[realindex]['je'] * newdatasource[realindex]['shuil']/100
      }
      let zsl=newdatasource.reduce((total,item)=>total+item.sl*1,0)
      props.formdata.hjsl.value = parseFloat(zsl).toFixed(2)
      let zje=newdatasource.reduce((total,item)=>total+item.je*1,0)
      props.formdata.hjje.value = parseFloat(zje).toFixed(2)
      props.handlechangeFormdata({...props.formdata} )
      // setDataSource(newdatasource)
      props.handgetmxdata(newdatasource)
    }


  //监听输入及联动
  const handleChangepopup = (e, transferarr, dataIndex, text, record, index) => {

    var tansferarr = transferarr;
    var selectrow = e;
    var newformdata = {}
    tansferarr.forEach(item => {
      record[item.target] = selectrow[item.origin]
    })
    var newdatasource = [...dataSource];
    const realindex = newdatasource.findIndex((item) => record.key === item.key);
    newdatasource[realindex] = record;
    //console.log("newdatasource", newdatasource)
    // setDataSource(newdatasource)
    props.handgetmxdata(newdatasource)

  }

  //监听选择
  const handleSelect = (e, dataIndex, text, record, index) => {
    var newdatasource = [...dataSource];
    newdatasource[index][dataIndex] = e;
    // setDataSource(newdatasource)
    props.handgetmxdata(newdatasource)
  }

    //监听选择
  const handleSelectNew = (e, transferarr, text, record, index,datas_key) => {
    var tansferarr = transferarr;
    var selectrow = e;
    var newformdata = {}
    tansferarr.forEach(item => {
      record[item.target] = selectrow[item.origin]
    })
    var newdatasource = [...dataSource];
    const realindex = newdatasource.findIndex((item) => record.key === item.key);
    newdatasource[realindex] = record;
    console.log("record", record)

    console.log("newdatasource", newdatasource)
    // setDataSource(newdatasource)
    props.handgetmxdata(newdatasource)
    
  }


    const handleAdd = () => {
      const uniqueId = uuidv4();
      var newData = { key: uniqueId }
      props.colmuns.forEach(item => {
      newData[item.dataIndex] =  item.defalut_v
      })
      newData.djzt='正常'
      newData.key=uniqueId
      newData.id=uniqueId
  
     setDataSource([...dataSource, newData]);
      props.handgetmxdata([...dataSource, newData])
      setCount(count + 1);
  
    };

  const handleSave = () => {
    if (type == 'add') {
      var result = {}
      for (let item in formdataoneepage) {
        result[item] = formdataoneepage[item].value
      }
      //console.log(props.datasource, result)
      // setDataSource(newData);
      props.handgetmxdata([...props.datasource, result])

      setifshowonepage('none')
    }
    else {
      var result = {}
      for (let item in formdataoneepage) {
        //console.log(item)
        result[item] = formdataoneepage[item].value
      }
      var newdatasource = [...dataSource];
      const realindex = newdatasource.findIndex((item) => selectedRows[0].key === item.key);
      //console.log("realindex", realindex)
      newdatasource[realindex] = result;
      //console.log("newdatasource", newdatasource)
      // setDataSource(newdatasource)
      props.handgetmxdata(newdatasource)
      
      setifshowonepage('none')
    }
  };

  const handleEdit = () => {
    if (selectedRows.length == 0) {
      openNotification_util("请选择要修改的行")
    }
    else {
      if (selectedRows.length > 1) {
        openNotification_util("只能选择一行进行修改")
      }
      else {
        setifshowonepage('block')
        setType('edit')
        // props.handgetmxdata(newdatasource)
      }

    }
  }
  const handleCopy = () => {
    if (selectedRows.length == 0) {
      openNotification_util("请选择要修改的行")
    }
    else {
      if (selectedRows.length > 1) {
        openNotification_util("只能选择一行进行修改")
      }
      else {
        const uniqueId = uuidv4();

        var newselecrows = { ...selectedRows[0] }
        newselecrows.id = uniqueId
        //console.log("selectedRowKeys", selectedRows[0])
        var newData = { key: uniqueId, ...newselecrows }
        //console.log("newData", newData)
        setDataSource([...dataSource, newData]);
        props.handgetmxdata([...dataSource, newData])
      }
    }
  }

  const setfieldonepage = (onekey, value, settype) => {
    //设置前要先设置formdataonepage结构
    console.log("formdataoneepage", formdataoneepage);
    if (settype == 'single') {
      var newitem = formdataoneepage[onekey]
      newitem.value = value
      let newformdata = Object.assign({}, formdataoneepage, { [onekey]: newitem });
      setformdataonepage(newformdata)
    }
    else if (settype == "muti") {
      var tansferarr = onekey;
      var selectrow = value;
      var newformdata = {}
      tansferarr.forEach(item => {
        var newitem = formdataoneepage[item.target]
        newitem.value = selectrow ? selectrow[item.origin] : ""
        newformdata = Object.assign({}, formdataoneepage, { [item.target]: newitem });
      })
      setformdataonepage(newformdata)
    }
    else if (settype == "single_new") {
      // console.log("formdataoneepage", formdataoneepage[onekey]);
      var newitem = formdataoneepage[onekey]
      newitem.value = value
      const OptionIndex = props.dynDatasObject[formdataoneepage[onekey]["datas_key"]].findIndex((item) => item.value === value);
      formdataoneepage[onekey].select_tansferarr.forEach(item => {
         formdataoneepage[item.target].value = props.dynDatasObject[formdataoneepage[onekey]["datas_key"]][OptionIndex][item.origin]
      })
      console.log("formdataoneepage", formdataoneepage);
      setformdataonepage({...formdataoneepage})
    }
    //console.log("onekey", onekey)
    //console.log("value", value)
  }



  const renderfileditem = () => {
    let formdataarr = []
    let formdata = {}
    props.colmuns.forEach(faritem => {
      formdata[faritem.dataIndex] = faritem
    })
    //console.log("formdata", formdata)
    for (var formitemkey in formdata) {
      formdata[formitemkey].inputType == "none" ? "" : formdataarr.push(formdata[formitemkey])
    }

    var renderstr = formdataarr.map(item => {
      var rtitem = item.input_type == "space_item" ?
        <div> &nbsp;&nbsp;&nbsp;
          <Customfielditem_hook form={formdata} item={{ inputType: "none" }}  dynDatasObject={props.dynDatasObject}
            handlechange={(key, value, settype) => { setfieldonepage(key, value, settype) }} />
        </div>
        :
        <Customfielditem_hook form={formdata} item={formdata[item.dataIndex]}  dynDatasObject={props.dynDatasObject}
          handlechange={(key, value, settype) => { setfieldonepage(key, value, settype) }} />

      return rtitem
    }
    )
    return renderstr
  }

  return (
    <div style={props.styleobj ? props.styleobj : {}}>


      {/* 单页编辑开始 */}
      <div style={{
        position: "fixed", width: "100vw", height: "100vh", left: "0", top: "0", display: ifshowonepage,
        backgroundColor: "rgba(0,0,0,0.8)", zIndex: "100", fontWeight: "800"
      }}>
        <div style={{
          width: "90%", height: "95%", position: 'absolute', backgroundColor: "white",top:"2%",left:"5%",
        }}>
          <div style={{ height: "2rem", backgroundColor: "#e7e5e5", color: "black", textIndent: "1rem" }}>
            单页表单
            &nbsp;&nbsp;&nbsp; <Button type="primary" style={{ marginTop: "0.2rem" }}
              onClick={e => setifshowonepage("none")}> 关 闭  </Button>
            &nbsp;&nbsp;&nbsp; <Button type="primary" style={{ marginTop: "0.2rem" }} onClick={e => { handleSave(type) }}
            > {type == 'add' ? '保 存' : '修 改'} </Button>
          </div>

    
                      <div style={{
            height: props.onepageheight ? props.onepageheight : Math.ceil(props.colmuns.length / 4) * 6 + "%",
            fontSize: "0.7rem", position: "relative", width: "96%", marginLeft: "2%", backgroundColor: "",
            textIndent: "1rem", display: "flex", justifyContent: "flex-start", alignItems: "center", flexWrap: "wrap"
          }}>
            {renderfileditem()}
          </div>
        </div>
        1</div>
      {/* 单页编辑结束 */}


      <div style={{ width: "80%", position: "sticky", top: "0%", left: "0%" }} >
        <Button onClick={handleAdd} style={{
          backgroundColor: "white",
          marginLeft: "0rem", color: "#a91f24", fontWeight: "800"
        }} >< FileAddOutlined />新增</Button>

        <Button onClick={handleDeletebatch} style={{
          backgroundColor: "white",
          marginLeft: "0.5rem", color: "#a91f24", fontWeight: "800"
        }} ><DeleteOutlined />删除</Button>

        <Button onClick={handleCopy} style={{
          backgroundColor: "white",
          marginLeft: "0.5rem", color: "#a91f24", fontWeight: "800"
        }} ><CopyOutlined />复制本行</Button>


        <Button onClick={e => { setifshowonepage(ifshowonepage == "none" ? "block" : "none"); setType('add') }} style={{
          backgroundColor: "white",
          marginLeft: "0.5rem", color: "#a91f24", fontWeight: "800"
        }} ><ExperimentOutlined />新增(单页)</Button>


        <Button onClick={handleEdit} style={{
          backgroundColor: "white",
          marginLeft: "0.5rem", color: "#a91f24", fontWeight: "800"
        }} ><ExperimentOutlined />编辑(单页)</Button>
{/* 

        <Button onClick={handlecloseplan} style={{
          backgroundColor: "white",
          marginLeft: "0.5rem", color: "#a91f24", fontWeight: "800"
        }} ><ExperimentOutlined />关闭计划</Button> */}


        {/* <Button onClick={handleSave} style={{
        backgroundColor: "white",
        marginLeft:  "0.5rem", color: "#a91f24", fontWeight: "800"
      }} >查看明细表数据</Button> */}
      </div>

      <Table style={{ width: "100%"}}
        rowSelection={rowSelection}
        bordered
        sticky
        pagination={{
         defaultPageSize: props.defaultPageSize ? props.defaultPageSize : 10,
    total: dataSource.length, pageSizeOptions: ['15', '30', '50', '110'], 
    position: ['bottomLeft']
}}
        scroll={{
          y: 600,
        }}
        size="small"
        dataSource={dataSource}
        columns={columns}
      />
    </div>
  );
};


export default Gpd_mx_hook;


